package com.zcah.db.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zcah.common.vo.R;
import com.zcah.db.DbSource;
import com.zcah.db.dbsource.DbSourceFactory;
import com.zcah.db.domain.ColumnProperty;
import com.zcah.db.domain.DbsourceDO;
import com.zcah.db.service.DbsourceService;
import com.zcah.db.vo.TableInfo;

@RestController
@RequestMapping("/v1/db")
public class DbController {

	@Autowired
	private DbsourceService dbsourceService;
	
	@RequiresAuthentication
	@GetMapping("/testConnection/{dbsourceId}")
	public R testConnection(@PathVariable int dbsourceId) throws Exception {
		DbsourceDO dbsource = dbsourceService.get(dbsourceId);
		try (DbSource instance = DbSourceFactory.getInstance(dbsource);) {
			String msg = instance.testConnection();
			return R.ok(msg);
		}
	}

	@RequiresAuthentication
	@GetMapping("/tables/{dbsourceId}")
	public List<TableInfo> getSchemaTables(@PathVariable int dbsourceId) throws Exception {
		DbsourceDO dbsource = dbsourceService.get(dbsourceId);
		try (DbSource instance = DbSourceFactory.getInstance(dbsource);) {
			List<TableInfo> schemasTables = instance.getSchemasTables();
			return schemasTables;
		}

	}

	@RequiresAuthentication
	@GetMapping("/tableColumns/{dbsourceId}")
	public List<ColumnProperty> getTableColumns(@PathVariable int dbsourceId, @RequestParam String fullTableName) throws Exception {
		DbsourceDO dbsource = dbsourceService.get(dbsourceId);
		try (DbSource instance = DbSourceFactory.getInstance(dbsource);) {
			return instance.getTableColumns(fullTableName);
		}
	}
}
